package com.cyt.chattlibrary.message.model;

import android.net.Uri;
import android.os.Parcelable;
import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author QiQi
 * @ClassName: MessageContent
 * @date 2018/10/20
 * @description
 */
public abstract class MessageContent implements Parcelable {
    private UserInfo userInfo;

    protected MessageContent() {
    }

    public MessageContent(byte[] data) {

    }

    /**
     * 把用户数据对象转换成JSON对象
     *
     * @return
     */
    public JSONObject getJSONUserInfo() {
        if (this.getUserInfo() != null && this.getUserInfo().getId() != null) {
            JSONObject jsonObject = new JSONObject();

            try {
                jsonObject.put("id", getUserInfo().getId());
                if (!TextUtils.isEmpty(getUserInfo().getName())) {
                    jsonObject.put("name", getUserInfo().getName());
                }

                if (getUserInfo().getPortraitUri() != null) {
                    jsonObject.put("portrait", getUserInfo().getPortraitUri());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return jsonObject;
        } else {
            return null;
        }
    }

    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

    /**
     * 把JSON对象转换成UseInfo对象
     *
     * @param jsonObject
     * @return
     */
    public UserInfo parseJsonToUserInfo(JSONObject jsonObject) {
        UserInfo info = null;
        String id = jsonObject.optString("id");
        String name = jsonObject.optString("name");
        String icon = jsonObject.optString("portrait");
        if (TextUtils.isEmpty(icon)) {
            icon = jsonObject.optString("icon");
        }

        if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(name)) {
            Uri portrait = icon != null ? Uri.parse(icon) : null;
            info = new UserInfo(id, name, portrait);
        }
        return info;
    }

    public abstract byte[] encode();

}
